package com.define.commons.common.utils;

import com.define.commons.common.constants.CommonConstants;
import lombok.Data;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.define.commons.common.dto.UserToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * JwtUtils
 * @Author xiewenlong
 * @Date 2018/12/6 18:12
 */
public class JwtUtils {

    /**
     * 私钥
     */
    private static String PRIVATE_SECRET = CommonConstants.JWT_PRIVATE_KEY;

    /**
     * 发行人
     * 谁发行由谁解析
     * 和私钥功能类似，当作二次加密使用
     */
    private static String ISSUER = "gzdefine";

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成token，过期时间单位秒
     */
    public static String generateToken(UserToken userToken, int expire) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(PRIVATE_SECRET);
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(ISSUER)
                .withExpiresAt(DateUtils.addSeconds(new Date(), expire))
                .withSubject(objectMapper.writeValueAsString(userToken));
        return builder.sign(algorithm);
    }

    /**
     * 验证token，并返回subject
     */
    public static UserToken getInfoFromToken(String token) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(PRIVATE_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        DecodedJWT jwt = verifier.verify(token);
        return objectMapper.readValue(jwt.getSubject(), UserToken.class);
    }
}
